package util.concurrent;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author 李栋
 * @version 1.0.0
 * @className CopyOnWriteArrayListTest.java
 * @createTime 2021年08月15日 12:33:00
 */
public class CopyOnWriteArrayListTest {

    private static final Logger logger = LoggerFactory.getLogger(CopyOnWriteArrayListTest.class);


    @Test
    public void test() {
        List<String> list = new CopyOnWriteArrayList<>();
        DemoOneRunnable demoOneRunnable = new DemoOneRunnable(list);
        DemoTwoRunnable demoTwoRunnable = new DemoTwoRunnable(list);
        Thread threadOne = new Thread(demoOneRunnable);
        threadOne.start();
        Thread threadTwo = new Thread(demoTwoRunnable);
        threadTwo.start();
    }

}

class DemoOneRunnable implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(DemoOneRunnable.class);


    private final List<String> list;

    public DemoOneRunnable(List<String> list) {
        this.list = list;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {

            logger.info(iterator.next());

        }
    }
}

class DemoTwoRunnable implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(DemoTwoRunnable.class);


    private final List<String> list;

    public DemoTwoRunnable(List<String> list) {
        this.list = list;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {

            logger.info(iterator.next());

        }
    }
}